package com.file.service.impl;

import com.file.msg.RequestData;
import com.file.msg.RequestMsg;
import com.file.service.UseService;
import com.file.sys.SysMsg;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

@Slf4j
@Service
public class IUseService implements UseService {
    @SneakyThrows
    @Override
    public RequestData upload(MultipartFile file, String dir) {
        FileOutputStream fileOutputStream =null;
        UUID uuid = UUID.randomUUID();
        ApplicationHome applicationHome = new ApplicationHome(this.getClass());
        String absolutePath = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath();

        File createFile = new File(absolutePath+"\\src\\main\\resources\\static");
        if(!createFile.exists()){
            boolean newFile = createFile.mkdir();
        }
        if(createFile.exists()){
            boolean b = createFile.canWrite();
            if(b){
                    fileOutputStream = new FileOutputStream(absolutePath+"\\src\\main\\resources\\static\\"+ uuid+".jpg");
                BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
                bufferedOutputStream.write(file.getBytes());
                    bufferedOutputStream.close();
                    fileOutputStream.close();
            }
        }

        return new RequestData(RequestMsg.SUCCESS_ADD_File,"http://localhost:8082/"+ uuid+".jpg");
    }
    @Override
    public RequestData del(String filename){
        ApplicationHome applicationHome = new ApplicationHome(this.getClass());
        String absolutePath = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath();
        File file = new File(filename);
        boolean delete = file.delete();
        if(delete){
           return new RequestData(RequestMsg.SUCCESS_DELETE_File,null);
        }
        return new RequestData(RequestMsg.ERROR_NOT_EXSIST_DIR,null);
    }

}
